<?php
/**
 * Created by PhpStorm.
 * User: xiong <1099446868@qq.com>
 * DateTime: 2018/12/21
 * TIME: 17:14
 */

namespace app\mobile\model;

use think\Db;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Cookie;
use think\Model;

class Mobile extends Model {

    public static function index($id){
        if(empty($id)){
            $index = self::getIndexByZ();
        }else{
            $index = self::getIndexData();
        }

        return $index;
    }

    public static function getIndexByZ(){
        if(Cache::has('mobile_zwdu_index')){
            $r = Cache::get('mobile_zwdu_index');
        }else{
            $r = Db::name('category')->select();
            //dump($category);
            foreach($r as $kk=>$vv){
                $book = Db::name('mobile_tuijian')->where('category', $vv['id'])->select();
                $r[$kk]['book'] = $book;
            }
            Cache::set('mobile_zwdu_index', $r, config('mobile_zwdu_index_time'));
        }
        return $r;
    }

    public static function getIndexData(){
        if(Cache::has('mobile_zh_index')){
            //Cache::rm('mobile_zh_index');
            $r = Cache::get('mobile_zh_index');
        }else{
            $xpath = config('xpath')['zh']['mobile']['index'];
            $html = curl_get($xpath['url']);
            $r = [];
            foreach($xpath['select'] as $k=>$v){
                $r[$k] = getContent($html, $v);
            }
            foreach($r['bianji'] as $k=>$v){
                $r['bianji2'][$k]['desc'] = getContent('<?xml encoding="UTF-8">'.$v, '//div[@class="desc"]',true);
                $r['bianji2'][$k]['bookname'] = getContent('<?xml encoding="UTF-8">'.$v, '//h3',true);
                $r['bianji2'][$k]['img'] = getContent('<?xml encoding="UTF-8">'.$v, '//img/@src',true);
                $r['bianji2'][$k]['other'] = getContent('<?xml encoding="UTF-8">'.$v, '//*[@class="other flex flex--justify"]');
            }
            $r['other']['boy'] = $r['boygirl'][0] ."\n". $r['boygirl'][1];
            $r['other']['girl'] = $r['boygirl'][2] ."\n". $r['boygirl'][3];
            $r['other']['wanben'] = $r['boygirl'][4];
            $r['other']['xinshu'] = $r['boygirl'][5] ."\n". $r['boygirl'][6];
            $r['bianji'] = $r['bianji2'];
            unset($r['bianji2']);
            unset($r['boygirl']);
            foreach($r['other'] as $k=>$v){
                $b = $v;
                $r['other'][$k] = [];
                $r['other'][$k]['img'] = getContent('<?xml encoding="UTF-8">'.$b, '//img/@data-src',true);
                $r['other'][$k]['bookname'] = getContent('<?xml encoding="UTF-8">'.$b, '//i',true);
            }
            //玄幻仙侠 都市娱乐 科幻历史 热门作品 各个榜单排第一个
            unset($r['lanmutuijian'][4]);
            unset($r['lanmutuijian'][5]);
            unset($r['lanmutuijian'][6]);
            foreach($r['lanmutuijian'] as $k=>$v){
                $r['lanmutuijian'][$k] = [];
                $r['lanmutuijian'][$k]['bookname'] = getContent('<?xml encoding="UTF-8">'.$v, '//h3',true);
                $r['lanmutuijian'][$k]['desc'] = getContent('<?xml encoding="UTF-8">'.$v, '//div[@class="desc"]',true);
                $r['lanmutuijian'][$k]['img'] = getContent('<?xml encoding="UTF-8">'.$v, '//div[@class="book-img-border"]/img/@data-src',true);
                $r['lanmutuijian'][$k]['author'] = getContent('<?xml encoding="UTF-8">'.$v, '//div[@class="other flex flex--justify"]');
                $r['lanmutuijian'][$k]['title'] = getContent('<?xml encoding="UTF-8">'.$v, '//span[@class="flex--fluid"]', true);
            }

            Cache::set('mobile_zh_index', $r, config('mobile_zh_index_time'));
        }
        //dump($r);exit;
        return $r;
    }

    public static function getSource(){
        if(Cookie::has('source')){
            $source = Cookie::get('source');
        }else{
            $source = 'zwdu';
        }
        return $source;
    }

    /**
     * @param $searchname
     * @return array|false|mixed|null|\PDOStatement|string|\think\Model
     *  先从自身数据库中搜索，搜不到再从远程搜索，本地搜到后显示小说详情页面，远程搜到后显示检索页面，检索页面根据用户
     *  的选择爬取
     */
    public static function getBookByBookName($searchname){

        $source = self::getSource();
        //dump($source);
        $book = self::isBookInMySelf($searchname, $source);
        if(!is_null($book)){
            return $book;
        }

        $xpath = config('xpath');
        //url中出现中文需要编码
        $url = $xpath[$source]['search']['url'] . urlencode($searchname);
        $search_html = curl_get($url);
        $fields = $xpath[$source]['search']['fields'];
        //dump($fields);exit;
        $books = getConFromHtml($search_html, $fields);
        $return['books'] = self::updateFields($books, $source);
        $return['searchname'] = $searchname;
        //获取末页
        $lastpage = $xpath[$source]['search']['field']['lastpage'];
        $lastpage = getContent($search_html, $lastpage);
        if(!empty($lastpage)){
            $lastpage = explode('page=', $lastpage);
            $lastpage = explode(' ', $lastpage[1]);
            $lastpage = (int)$lastpage[0];
            $return['lastpage'] = $lastpage;
        }
        //dump($return);exit;
        return $return;
    }

    public static function isBookInMySelf($bookname, $source){
        $book = [];
        if(Cache::has('bookname_'.$bookname)){
            $book = Cache::get('bookname_'.$bookname);
        }else{
            $book = Db::name('bookname')
                ->where('bookname|author', $bookname)
                ->find();
            if(!is_null($book)){

                $category = self::category($source, $book['category']);
                $book = array_merge($book, $category);
                Cache::set('bookname_'.$bookname, $book, config('cache_time'));
            }

        }
        return $book;
    }

    public static function updateFields($return, $source){
        if($source == 'zwdu'){
            foreach($return as $k=>$v){
                $link = explode('"', $v['link']);
                $return[$k]['bookname'] = $link[5];
                $link = explode('/', $link[3]);
                $link = '/'.$link[3].'/'.$link[4].'/';
                $return[$k]['link'] = $link;

                $return[$k]['author'] = trim($v['author']);
                $return[$k]['source'] = 1;
            }
        }

        return $return;
    }
    /**
     * @param $source  book来源
     * @param $cid category值
     * @return mixed
     */
    public static function category($source, $cid){
        $category = Config::get('category');
        $arr = [];
        $arr['category'] = $category[$source][$cid]['name'];
        $arr['category_url'] = $category[$source][$cid]['url'];
        return $arr;
    }

    public static function getBookById($id){

        if(Cache::has('book_'.$id)){
            return Cache::get('book_'.$id);
        }else{
            $arr = Db::name('bookname')
                ->where('id', $id)
                ->find();
            $category = self::category($arr['source'], $arr['category']);
            $arr = array_merge($arr, $category);
            Cache::set('book_'.$id, $arr, config('cache_time'));
            return $arr;
        }
    }

    //获取第一章
    public static function getStartChapter($id, $table){
        return Db::name($table)->field('id as sid,title as stitle')->where('bid', $id)->find();
    }
    //获取最后一章
    public static function getEndChapter($id, $table){
        return Db::name($table)->field('id as eid,title as etitle')->where('bid', $id)->order('id desc')->find();
    }

    public static function getCatalogsByBid($id, $table){
        if(Cache::has('catalogs_'. $id)){
            return Cache::get('catalogs_'. $id);
        }else{

            $catalog = Db::name($table)
                ->field('id,bid,bookname,title,url')
                ->where('bid', $id)
                ->cache('catalogs_'. $id, config('catalogs_time'))
                ->select();

            return $catalog;
        }
    }

    public static function getCatalogCount($id, $table){
        $count = Db::name($table)->where('bid', $id)->count();
        return $count;
    }

    public static function content($bid, $id, $table) {
        if (Cache::has('book_' . $bid)) {
            $book = Cache::get('book_' . $bid);
            $source = $book['source'];
        } else {
            $arr = Db::name('bookname')
                ->where('id', $bid)
                ->find();
            $category = self::category($arr['source'], $arr['category']);
            $book = array_merge($arr, $category);
            Cache::set('book_' . $bid, $book, config('cache_time'));
            $source = $book['source'];
        }


        $catalogs = self::getCatalogsByBid($bid, $table);  //所有目录
        $catalog = self::getCatalogById($id, $table);  //本章记录

        //上一章和下一章
        foreach ($catalogs as $k => $v) {
            if ($catalog['id'] == $v['id']) {
                $current = $k;
            }
        }
        $prev = [];
        $next = [];
        if ($current >= 1) {
            $prev = $current - 1;
            $prev = $catalogs[$prev];
            $prev['bid'] = $bid;
        }
        $count = self::getCatalogCount($bid, $table);
        if ($current + 1 < $count) {
            $next = $current + 1;
            $next = $catalogs[$next];
            $next['bid'] = $bid;
        }

        if ($catalog['status'] == 1) {
            //说明数据库中有值,且已经缓存了，将其读出
            $content = gzuncompress($catalog['content']);
        } else {

            //抓取内容
            if ($source == 'zwdu') {
                $url = 'https://www.' . $source . '.com' . $catalog['url'];
                $html = curl_get($url);
                $xpath = config('xpath');
                $select = $xpath[$source]['content'];
                $content = getContent($html, $select);
            }
            if (!empty($content)) {
                $content = ltrim($content, '<div id="content">');
                $content = rtrim($content, '</div>');
                //更新数据库，但是没有将其缓存在文件中，需要再次刷新才能缓存到文件里
                Db::name($table)->where('id', $id)->update(['content' => gzcompress($content), 'status' => 1]);
            } else {
                $content = '获取本章失败，请刷新重试！';
            }

        }


        $book['content'] = $content;
        $book['wordnum'] = mb_strlen($content);
        $book['title'] = $catalog['title'];
        $book['prev'] = $prev;
        $book['next'] = $next;

        return $book;
    }

    //获取单个章节
    public static function getCatalogById($id, $table){
//        if(Cache::has('catalog_'. $id)){
//            return Cache::get('catalog_'. $id);
//        }else{
            $catalog = Db::name($table)
                ->where('id', $id)
//                ->cache('catalog_'. $id, config('catalog_time'))
                ->find();

            return $catalog;
//        }
    }
}